package com.bluesky.mq;

import com.bluesky.mq.mapper.MsgMapper;
import com.bluesky.mq.retry.DefaultMqSendRetry;
import com.bluesky.mq.retry.MqSendRetry;
import com.bluesky.mq.sender.DefaultMsgSender;
import com.bluesky.mq.sender.IMsgSender;
import com.bluesky.mq.sender.MqSendRetryJob;
import com.bluesky.mq.service.IMsgService;
import com.bluesky.mq.service.impl.MsgServiceImpl;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@MapperScan(basePackageClasses = MsgMapper.class)
@EnableScheduling
public class MqConfiguration {


    @Bean
    @ConditionalOnMissingBean
    public MqSendRetry mqSendRetry(){
        return new DefaultMqSendRetry();
    }

    @Bean
    @ConditionalOnMissingBean
    public IMsgSender msgSender(IMsgService msgService, MqSendRetry mqSendRetry){
        return new DefaultMsgSender(msgService, mqSendRetry,this.mqExector());
    }

    @Bean
    public IMsgService msgService(){
        return new MsgServiceImpl();
    }


    @Bean
    public MqSendRetryJob mqSendRetryJob(IMsgService msgService, IMsgSender msgSender){
        return new MqSendRetryJob(msgService,msgSender);
    }
    @Bean
    public ThreadPoolTaskExecutor mqExector(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setThreadNamePrefix("ThreadPool-mqExecutor-");
        threadPoolTaskExecutor.setCorePoolSize(Runtime.getRuntime().availableProcessors()*4);
        threadPoolTaskExecutor.setMaxPoolSize(Runtime.getRuntime().availableProcessors()*8);
        threadPoolTaskExecutor.setQueueCapacity(10000);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolTaskExecutor;
    }
}
